<template>
    <div class="tableView">
        <el-table
            :data="tableData"
            :class="stripe ? 'stripe w-100' : 'w-100'"
            @row-click="rowClick"
            :border="border"
            :stripe="stripe"
            tooltip-effect="light"
            show-overflow-tooltip
            @sort-change="sortChange"
        >
            <el-table-column width="55" v-if="checkbox" align="center">
                <template #header>
                    <div :class="headerClass" @click="selectAll"></div>
                </template>
                <template #default="{ row }">
                    <div :class="getCheckbox(row)" @click="select(row)"></div>
                </template>
            </el-table-column>
            <el-table-column width="55" v-if="radio" align="center">
                <template #default="{ row }">
                    <div :class="getRadio(row)"></div>
                </template>
            </el-table-column>
            <el-table-column
                v-for="item in propList"
                :key="item.id"
                :prop="item.prop"
                :label="item.label"
                :min-width="getWidth(item)"
                align="center"
                :fixed="getFixd(item)"
                :sortable="item.sortable"
                show-overflow-tooltip
            >
                <template #default="{ row, $index }">
                    <div v-if="item.operate" class="fr-ac-jc">
                        <el-popover
                            v-for="child in getOperate(item.operate, 0)"
                            :key="child.id"
                            :visible="row[`isTrue${child.id}`]"
                            trigger="click"
                            :disabled="getDisabled(child)"
                            placement="left"
                            width="240"
                        >
                            <template #reference>
                                <div
                                    class="mx-5 px-10 radius-4"
                                    :style="operateColor(child, row)"
                                    @click="onOpen(row, child)"
                                >
                                    {{ child.label }}
                                </div>
                            </template>
                            <div>
                                <p class="fr-ac-jsb">
                                    <span>提示</span>
                                    <span
                                        class="fs-10"
                                        @click="onClose(row, child)"
                                        >×</span
                                    >
                                </p>
                                <p class="py-10 t-c">{{ child.tooltip }}</p>
                                <div class="fr-ac-jc">
                                    <div
                                        class="mx-10 border py-3"
                                        :style="white"
                                        @click="onClose(row, child)"
                                    >
                                        取消
                                    </div>
                                    <div
                                        class="mx-10 border py-3"
                                        :style="white"
                                        @click="onSure(row, child)"
                                    >
                                        确定
                                    </div>
                                </div>
                            </div>
                        </el-popover>
                        <el-dropdown
                            placement="bottom"
                            v-if="item.operate.length > 4"
                            @command="command"
                        >
                            <div
                                class="more mx-5 px-10 radius-4"
                                :style="purple"
                            >
                                更多
                            </div>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item
                                        v-for="child in getOperate(
                                            item.operate,
                                            1
                                        )"
                                        :key="child.id"
                                        :command="{
                                            row: row,
                                            child: child,
                                        }"
                                    >
                                        {{ child.label }}
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                    <div v-if="item.status" class="w-100 ellipsis-1">
                        <span
                            v-html="getStatus(item.status, $index, '信息')"
                        ></span>
                        <span
                            v-html="getStatus(item.status, $index, '专业')"
                        ></span>
                        <span
                            v-html="getStatus(item.status, $index, '提交')"
                        ></span>
                        <span
                            v-html="getStatus(item.status, $index, '填报')"
                        ></span>
                        <span
                            v-html="getStatus(item.status, $index, '生成')"
                        ></span>
                        <span
                            v-html="getStatus(item.status, $index, '审核')"
                        ></span>
                        <span
                            v-html="getStatus(item.status, $index, '结单')"
                        ></span>
                        <span
                            v-html="getStatus(item.status, $index, '录取')"
                        ></span>
                    </div>
                    {{ row[item.prop] }}
                </template>
            </el-table-column>
        </el-table>
        <div :class="`pt-${spacing}`" :style="getPaging()">
            <el-pagination
                v-model:current-page="current"
                v-model:page-size="size"
                background
                :layout="layout"
                :total="total"
                @current-change="currentChange"
            />
            <el-select
                v-model="optionsValue"
                placeholder="page"
                class="w-10 pl-10"
                v-if="jumper"
                @change="jumperChange"
            >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
    </div>
</template>
<script>
import { defineComponent, nextTick, onMounted, ref, watch } from "vue";
import { blue, white, purple, green } from "@/comment/data";
import { propWidth,getIcon } from "@/comment/method";
export default defineComponent({
    props: {
        data: {
            type: Array,
            default: () => [],
        },
        total: {
            type: Number,
            default: 100,
        },
        propList: {
            type: Array,
            default: () => [
                // {
                //     prop: "",
                //     label: "",
                //     id:1,
                //     operate: [
                //         {
                //             id: 1,
                //             label: "",
                //             isPopover: false,
                //             tooltip: "",
                //             style: red,
                //             void: (val) => {},
                //         },
                //     ],
                // },
            ],
        },
        //操作按钮的最多展示数量
        operateNum: {
            type: Number,
            default: 4,
        },
        //距分页器的距离(最小值1,最大值100)
        spacing: {
            type: Number,
            default: 50,
        },
        //表格当前页
        currentPage: {
            type: Number,
            default: 1,
        },
        //表格当前页的条数
        pageSize: {
            type: Number,
            default: 10,
        },
        //默认分页器布局
        layout: {
            type: String,
            default: "prev, pager, next , total",
        },
        jumper: {
            type: Boolean,
            default: false,
        },
        //默认分页器位置
        paging: {
            type: String,
            default: "left",
        },
        //多选
        checkbox: {
            type: Boolean,
            default: false,
        },
        //单选
        radio: {
            type: Boolean,
            default: false,
        },
        //只有checkbox为true时生效
        isRow: {
            type: Boolean,
            default: false,
        },
        border: {
            type: Boolean,
            default: false,
        },
        stripe: {
            type: Boolean,
            default: false,
        },
    },
    emits: ["itemClick", "pageClick", "jumperClick", "sortClick"],
    methods: {
        //获取表格宽度
        getWidth(val) {
            // 如果 val.operate 不存在或为空
            if (!val.operate?.length) {
                return (val.width = propWidth(val.prop));
            }

            // 计算操作项的总宽度，并根据 operateNum 做调整
            const totalWidth = val.operate
                .slice(0, this.operateNum)
                .reduce((sum, { label }) => {
                    return sum + label.length * 14 + 30;
                }, 0);

            // 根据操作项是否超出 operateNum 调整宽度
            return val.operate.length > this.operateNum
                ? totalWidth + 83
                : totalWidth + 25;
        },
        //多选表格header图标展示
        updateHeaderCheckboxState() {
            const hasTrue = this.tableData.some((item) => item.isTrue === true);
            const allTrue = this.tableData.every(
                (item) => item.isTrue === true
            );
            const classMap = {
                true_true: this.xuanzhong,
                true_false: this.weiquanbuxuanzhong,
                false: this.weixuanzhong,
            };
            this.headerClass = hasTrue
                ? classMap[`${hasTrue}_${allTrue}`]
                : classMap.false;
        },
        //默认分页器位置
        getPaging() {
            return {
                display: "flex",
                flexDirection: "row",
                alignItems: "center",
                justifyContent: this.paging,
            };
        },
        //分页器点击
        currentChange(val) {
            this.$emit("pageClick", val);
        },
        sizeChange(val) {
            console.log(val, "11111111111111111");
        },
        jumperChange(val) {
            this.$emit("jumperClick", val);
            this.current = 1;
        },
        //当某一行被点击时会触发该事件
        rowClick(val) {
            if (!val) return; // 空值保护
            // 处理复选框模式
            if (this.checkbox && this.isRow) {
                val.isTrue = !val.isTrue;
                this.updateHeaderCheckboxState(); // 更语义化的方法名
                this.getSelected();
                this.$emit("itemClick", this.getSelected());
                return;
            }
            // 处理单选按钮模式
            if (this.radio) {
                // 记录当前选中状态
                const wasSelected = val.isTrue;
                this.clearAllSelections();
                // 如果之前已选中则取消，否则选中
                val.isTrue = !wasSelected;
                this.$emit("itemClick", this.getSelected());
            }
        },
        //多选表格图标展示
        getCheckbox(val) {
            return val.isTrue ? this.xuanzhong : this.weixuanzhong;
        },
        //单选表格图标展示
        getRadio(val) {
            return val.isTrue ? this.selectedCopy : this.danxuanweixuanzhong;
        },
        //表格清除选择项
        clearAllSelections() {
            this.tableData.forEach((item) => (item.isTrue = false));
        },
        //表格多选点击
        select(val) {
            val.isTrue = !val.isTrue;
            this.updateHeaderCheckboxState();
            this.getSelected();
            this.$emit("itemClick", this.getSelected());
        },
        //表格全选和全不选
        selectAll() {
            this.tableData.forEach((item) => {
                item.isTrue = !this.isAllSelected;
            });
            this.isAllSelected = !this.isAllSelected;
            this.updateHeaderCheckboxState();
            this.getSelected();
            this.$emit("itemClick", this.getSelected());
        },
        //表格选中项获取
        getSelected() {
            return this.tableData.filter((item) => item.isTrue == true);
        },
        //表格定位获取
        getFixd(val) {
            switch (val.label) {
                case "操作":
                case "":
                    return "right";
                default:
                    return false;
            }
        },
        //是否禁用弹出框
        getDisabled(val) {
            return val.isPopover ? false : true;
        },
        //操作数组截取处理
        getOperate(val, num) {
            switch (num) {
                case 0:
                    return val.slice(num, 4);
                case 1:
                    return val.slice(4);
            }
        },
        //打开弹出框
        onOpen(row, childVal) {
            this.tableData.forEach((item) => {
                Object.keys(item)
                    .filter((key) => key.startsWith("isTrue"))
                    .forEach((key) => (item[key] = false));
            });
            row[`isTrue${childVal.id}`] = true;
            childVal.void(row);
        },
        onClose(row, childVal) {
            row[`isTrue${childVal.id}`] = false;
        },
        onSure(row, childVal) {
            row[`isTrue${childVal.id}`] = false;
        },
        //下拉项点击时触发
        command(val) {
            console.log(val.tooltip, "33333333333333333333333");
        },
        operateColor(val, row) {
            // const styleString = Object.entries(val.style)
            //     .map(([key, value]) => {
            //         // 转换 JavaScript 驼峰式属性名为 CSS 短横线风格属性名
            //         const cssKey = key.replace(/([A-Z])/g, "-$1").toLowerCase();
            //         return `${cssKey}: ${value}`;
            //     })
            //     .join(";");
            if (val.style === "tabulation") {
                return !row.assistant && !row.check && !row.filling
                    ? green
                    : purple;
            } else {
                return val.style;
            }
        },
        sortChange(val) {
            this.$emit("sortClick", val);
        },
        // 封装成一个通用函数来渲染每个状态
        getStatus(val, ind, title) {
            let getClass = val[ind][title] ? "" : "red";
            let arr1 = `<span class="${getIcon("duigou")}"></span>`;
            let arr2 = `<span class="${getIcon("cuo")} red"></span>`;
            return `<span>
                        <span class="${getClass}">${title}</span>
                        <span>${val[ind][title] ? arr1 : arr2}</span>
                    </span>`;
        },
        clearClick() {
            this.tableData.forEach((item) => item.isTrue = false);
            this.isAllSelected=false
            this.headerClass=this.weixuanzhong
        },
    },
    mounted() {
        this.updateHeaderCheckboxState();
    },
    setup(props) {
        const tableData = ref(props.data);
        const current = ref(props.currentPage);
        const size = ref(props.pageSize);
        const options = [
            {
                value: 15,
                label: "15",
            },
            {
                value: 25,
                label: "25",
            },
            {
                value: 30,
                label: "30",
            },
            {
                value: 50,
                label: "50",
            },
            {
                value: 1000,
                label: "all",
            },
        ];
        const optionsValue = ref(15);
        const headerClass = ref("");
        const isAllSelected = ref(false);
        const xuanzhong = `${getIcon("quanxuan-xuanzhong")} selectbox`;
        const weixuanzhong = `${getIcon("quanxuan-weixuanzhong")} select`;
        const weiquanbuxuanzhong = `${getIcon("weiquanbuxuanzhong")} selectbox`;
        const danxuanweixuanzhong = `${getIcon("danxuanweixuanzhong")} select`;
        const selectedCopy = `${getIcon("selected-copy")} selectbox`;
        watch(
            () => props.data,
            (newData) => {
                tableData.value = newData;
            }
        );
        watch(
            () => props.currentPage,
            (newCurrent) => {
                current.value = newCurrent;
            }
        );
        watch(
            () => props.pageSize,
            (newSize) => {
                size.value = newSize;
            }
        );
        return {
            tableData,
            current,
            size,
            options,
            optionsValue,
            headerClass,
            isAllSelected,
            blue,
            getIcon,
            xuanzhong,
            weixuanzhong,
            weiquanbuxuanzhong,
            danxuanweixuanzhong,
            selectedCopy,
            white,
            purple,
        };
    },
});
</script>

<style lang="scss" scoped>
.tableView {
    .select:hover {
        color: #409eff;
    }
    .selectbox {
        color: #409eff;
    }
    .more {
        &:hover,
        &:focus {
            outline: none;
        }
    }
    .el-dropdown {
        line-height: 23px;
    }
    .stripe :deep(.el-table__header) {
        --el-table-header-bg-color: #f2f2f2; /* 设置你想要的背景颜色 */
    }
    :deep(.el-tooltip) {
        max-width: 1000px;
    }
}
</style>
